package com.cloud.utils.common;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * @author: mengxiangzhong
 * @date: 2023/11/13 13:42
 * @DES: http返回工具类
 **/
@Slf4j
public class ResponseFormatter {

    /**
     * 格式化返回的response
     * @param response
     */
    public static void  initResponse(HttpServletResponse response, Object  obj)  {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");

        try {
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(obj));
            writer.close();
        } catch (Exception e) {
            log.info("HttpServletResponse Formatter Erroe : {} ",e.getMessage());
        }
    }


    /**
     * 设置浏览器下载响应头
     * @param response
     * @param fileName
     */
    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
